<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>聊天界面</h2>
      <button @click="logout" class="logout-btn">退出登录</button>
    </div>
    
    <div class="chat-content">
      <!-- 好友列表 -->
      <div class="friends-list">
        <h3>好友列表</h3>
        <div 
          v-for="friend in friends" 
          :key="friend" 
          :class="['friend-item', selectedFriend === friend ? 'selected' : '']"
          @click="selectFriend(friend)"
        >
          {{ friend }}
        </div>
        <div 
          class="friend-item public-chat" 
          :class="selectedFriend === 'public' ? 'selected' : ''"
          @click="selectFriend('public')"
        >
          公共聊天室
        </div>
      </div>
      
      <!-- 聊天区域 -->
      <div class="chat-main">
        <div class="chat-title">
          {{ selectedFriend === 'public' ? '公共聊天室' : `与 ${selectedFriend} 聊天` }}
        </div>
        
        <div class="chat-messages" ref="messagesContainer">
          <div 
            v-for="message in filteredMessages" 
            :key="message.timestamp + message.sender + message.receiver"
            :class="['message', message.sender === username ? 'sent' : 'received']"
          >
            <div class="message-sender">{{ message.sender }}</div>
            <div class="message-content">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <div class="chat-input-area">
          <input 
            v-model="message" 
            @keyup.enter="sendMessage" 
            placeholder="输入消息..." 
            class="message-input"
          />
          <button @click="sendMessage" class="send-btn">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

export default {
  data() {
    return {
      messages: [],
      message: '',
      username: '',
      stompClient: null,
      friends: [], // 好友列表
      selectedFriend: 'public', // 默认选中公共聊天室
      onlineUsers: [] // 在线用户列表
    }
  },
  computed: {
    // 根据选中的好友过滤消息
    filteredMessages() {
      if (this.selectedFriend === 'public') {
        // 公共聊天室只显示没有receiver的消息
        return this.messages.filter(msg => !msg.receiver);
      } else {
        // 私聊显示与当前好友相关的消息
        return this.messages.filter(msg => 
          (msg.sender === this.username && msg.receiver === this.selectedFriend) ||
          (msg.sender === this.selectedFriend && msg.receiver === this.username)
        );
      }
    }
  },
  async mounted() {
    // 检查是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/')
      return
    }
    
    // 获取用户信息
    try {
      const response = await axios.get('/auth/userInfo', {
        headers: { Authorization: token }
      })
      if (response.data.code === 200) {
        this.username = response.data.data.username || response.data.data.account
        
        // 模拟好友列表数据
        this.loadFriends();
        
        this.initWebSocket()
      } else {
        localStorage.removeItem('token')
        this.$router.push('/')
      }
    } catch (error) {
      localStorage.removeItem('token')
      this.$router.push('/')
    }
  },
  methods: {
    initWebSocket() {
      try {
        // 继续使用/ws路径
        const socket = new SockJS('/ws')
        this.stompClient = Stomp.over(socket)
        
        // 配置调试信息
        this.stompClient.debug = (str) => {
          console.log('STOMP: ' + str)
        }
        
        this.stompClient.connect({}, () => {
          console.log('WebSocket连接成功')
          // 订阅公共频道
          this.stompClient.subscribe('/topic/public', (message) => {
            const chatMessage = JSON.parse(message.body)
            this.messages.push(chatMessage)
            this.updateOnlineUsers(chatMessage)
            this.scrollToBottom()
          })
          
          // 订阅私有消息频道
          this.stompClient.subscribe('/user/queue/messages', (message) => {
            const chatMessage = JSON.parse(message.body)
            this.messages.push(chatMessage)
            this.scrollToBottom()
          })
          
          // 通知服务器用户已加入
          this.stompClient.send('/app/chat.newUser', {}, JSON.stringify({
            sender: this.username,
            type: 'JOIN'
          }))
        }, (error) => {
          console.error('WebSocket连接错误:', error)
          // 添加重连逻辑
          setTimeout(() => {
            console.log('尝试重新连接WebSocket...')
            this.initWebSocket()
          }, 3000)
        })
        
        // 添加连接关闭处理
        socket.onclose = (event) => {
          console.log('WebSocket连接已关闭:', event.code, event.reason)
        }
      } catch (error) {
        console.error('初始化WebSocket失败:', error)
      }
    },
    
    loadFriends() {
      // 在实际应用中，这里应该从后端API获取好友列表
      // 这里模拟一些数据
      this.friends = ['张三', '李四', '王五', '赵六']
      // 移除当前用户自己
      this.friends = this.friends.filter(friend => friend !== this.username)
    },
    
    selectFriend(friend) {
      this.selectedFriend = friend
      this.scrollToBottom()
    },
    
    updateOnlineUsers(chatMessage) {
      // 处理用户加入和离开事件，更新在线用户列表
      if (chatMessage.type === 'JOIN' && !this.onlineUsers.includes(chatMessage.sender)) {
        this.onlineUsers.push(chatMessage.sender)
      } else if (chatMessage.type === 'LEAVE' && this.onlineUsers.includes(chatMessage.sender)) {
        this.onlineUsers = this.onlineUsers.filter(user => user !== chatMessage.sender)
      }
    },
    
    sendMessage() {
      if (!this.message.trim()) {
        // 显示提示信息
        alert('消息内容不能为空！')
        return
      }
      
      if (this.stompClient) {
        const chatMessage = {
          sender: this.username,
          content: this.message.trim(),
          type: 'CHAT'
        }
        
        // 如果选择了特定好友，则发送私聊消息
        if (this.selectedFriend && this.selectedFriend !== 'public') {
          chatMessage.receiver = this.selectedFriend
          this.stompClient.send('/app/chat.sendPrivate', {}, JSON.stringify(chatMessage))
        } else {
          // 否则发送到公共频道
          this.stompClient.send('/app/chat.sendMessage', {}, JSON.stringify(chatMessage))
        }
        
        this.message = ''
      }
    },
    
    logout() {
      // 通知服务器用户离开
      if (this.stompClient) {
        this.stompClient.send('/app/chat.newUser', {}, JSON.stringify({
          sender: this.username,
          type: 'LEAVE'
        }))
        this.stompClient.disconnect()
      }
      
      // 清除本地token
      localStorage.removeItem('token')
      
      // 跳转到登录页面
      this.$router.push('/')
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messagesContainer) {
          this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight
        }
      })
    },
    
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleTimeString()
    }
  },
  
  beforeUnmount() {
    // 组件卸载时断开WebSocket连接
    if (this.stompClient) {
      this.stompClient.disconnect()
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #4CAF50;
  color: white;
  border-bottom: 1px solid #eee;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.logout-btn:hover {
  background-color: #d32f2f;
}

.chat-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 好友列表样式 */
.friends-list {
  width: 250px;
  background-color: #f5f5f5;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.friends-list h3 {
  padding: 15px 20px;
  margin: 0;
  background-color: #e9e9e9;
  border-bottom: 1px solid #ddd;
  font-size: 16px;
}

.friend-item {
  padding: 12px 20px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: background-color 0.2s;
}

.friend-item:hover {
  background-color: #e3f2fd;
}

.friend-item.selected {
  background-color: #bbdefb;
  font-weight: bold;
}

.public-chat {
  margin-top: auto;
  background-color: #e0e0e0;
}

/* 聊天主区域样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-title {
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #eee;
  font-weight: bold;
  font-size: 16px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 70%;
}

.message.sent {
  background-color: #dcf8c6;
  margin-left: auto;
}

.message.received {
  background-color: white;
  border: 1px solid #ddd;
}

.message-sender {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.message-content {
  font-size: 16px;
  word-wrap: break-word;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.chat-input-area {
  display: flex;
  padding: 20px;
  border-top: 1px solid #eee;
  background-color: white;
}

.message-input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  margin-right: 10px;
}

.message-input:focus {
  outline: none;
  border-color: #4CAF50;
}

.send-btn {
  padding: 12px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.send-btn:hover {
  background-color: #45a049;
}
</style>